package com.chhuang.sync;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.chhuang.bean.QueryTermBean;
import com.chhuang.common.Assert;
import com.chhuang.common.DataOperateAbstract;

/**
 * 全量同步数据库表类
 * @author HuangChen
 *
 */
public class FullSyncThread extends DataOperateAbstract implements Runnable {
	private static final Log LOG = LogFactory.getLog(FullSyncThread.class);
	
	protected String fromTable = null;
	protected String toTable = null;
	protected QueryTermBean initQueryTermBean = null;
	protected String[] selectColumns = null;
	
	/**
	 * 构造函数
	 * @param fromTable 来源表
	 * @param toTable 目的表
	 * @param initQueryTermBean 初始化查询条件（如：modifyTimeColumn>=?和 Timestamp(2016-01-01)）
	 * @param selectColumns 需要查询字段，为空时表示查询所有字段
	 */
	public FullSyncThread(String fromTable, String toTable, QueryTermBean initQueryTermBean, String... selectColumns){
		this.fromTable = fromTable;
		this.toTable = toTable;
		this.initQueryTermBean = initQueryTermBean;
		this.selectColumns = selectColumns;
	}

	@Override
	public void run() {
		if(Assert.isInvalidString(fromTable) || Assert.isInvalidString(toTable)){
			return ;
		}

		LOG.info("-----table ("+fromTable+"->"+toTable+") start sync-----");
		
		Connection fromConn = c3p0Helper.getConnection(c3p0Helper.getDataBaseName(0));
		Connection toConn = c3p0Helper.getConnection(c3p0Helper.getDataBaseName(1));
		
		//查找oracle数据库中fromTable表数据
		PreparedStatement ps = this.find(fromConn, fromTable, initQueryTermBean, selectColumns);
		ResultSet rs = this.getResultSet(ps);
		
		//清空mysql数据库toTable表数据
		this.truncate(toConn, toTable);
		
		//把数据写入mysql数据库toTable表
		boolean result = this.save(toConn, toTable, rs, null);
		
		c3p0Helper.closes(toConn);
		c3p0Helper.closes(fromConn, ps, rs);
		
		if(result){
			LOG.info("-----table ("+fromTable+"->"+toTable+") synchronized success-----");
		}else{
			LOG.info("-----table ("+fromTable+"->"+toTable+") Synchronous failure-----");
		}
	}
	
}
